<style type="text/css">
body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 9px;
  color: #333;
}
</style>
<input type="button" id="launchAll" value="Lancer"/>
<input type="button" id="pause" value="Pause"/>
<?php use_javascript('jquery/js/jquery-1.5.1.min.js') ?>

<ul>
<?php $id=0; foreach ($communesListe as $commune): $id++;?>
  <li class="communeblock" id="url-<?php echo $id ?>">
    <strong><?php echo $commune['title'] ?></strong>
    <span class="url"><?php echo $commune['url']; ?></span>
    <div class="repport">ready</div>
  </li>
<?php endforeach; ?>
</ul>

<script type="text/javascript">
$(function(){
  $('.communeblock').click(function(){
    currentDep = $(this);
    var id = $(this).attr('id');
    
    $.ajax({
      url: '/jckLocationTools/listeCommuneURL',
      data: {
        url: $(this).find('span').text()
      },
      success: function(data){

        currentDep.find('div.repport').html(data);
        currentDep.unbind('click');
        currentDep.find('div.repport li.commune').bind('click', updateCommune);
        currentDep.find('div.repport li.commune').first().trigger('click');
        currentDep = currentDep.next();
      }
    });
  });
});

var auto        = false;
var current     = null;
var currentDep  = null;


$(function(){
  $('#launchAll').bind('click', function(){
    auto = true;
    updateBlock();
  });

  $('#pause').bind('click', function(){
    auto = false;
  });

  
});
function updateBlock(){
  if( currentDep == null ){
    currentDep = $('.communeblock').first();
  }
  currentDep.trigger('click');
}
function updateCommune(){
  current = $(this);

  var commune = $(this).find('strong').text();
  var insee   = $(this).find('span').text();
  var cp      = $(this).find('em').text();

  $.ajax({
    url: "/jckLocationTools/synchronizeCommune",
    data: {
      commune: commune,
      insee: insee,
      cp: cp
    },
    success: function(data){

      current.css('color', '#fff');
      if( data == 'OK' ){
        current.css('background', '#009900');
        current.fadeOut();
      } else if ( data == 'UNCHANGE' ){
        current.css('background', '#999999');
        current.fadeOut();
      } else {
        current.css('background', '#990000');
      }
      current.unbind('click');

      current = current.next();
      //console.info('Next commune: ' + current.attr('id'));
      if( current.attr('id') == undefined ){
        console.info('Département suivant');
        console.debug(currentDep);
        currentDep.trigger('click');
      } else {
        current.trigger('click');
      }
    }
  });
}

/*
function updateAll(){
  if( !auto ) return;

  if( current == null ){
    current = $('#listeCommune li').first();
  }
  current.trigger('click');
}
*/
</script>


